<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'order:flow:fh:m8OrderFlowFh:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #m8OrderFlowFhRdsList>
        <BasicTable
          @register="registerM8OrderFlowFhRdsTable"
          @row-click="handleM8OrderFlowFhRdsRowClick"
        />
        <a-button
          class="mt-2"
          @click="handleM8OrderFlowFhRdsAdd"
          v-auth="'order:flow:fh:m8OrderFlowFh:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsOrderFlowFhM8OrderFlowFhForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    M8OrderFlowFh,
    m8OrderFlowFhSave,
    m8OrderFlowFhForm,
  } from '/@/api/m8/order/flow/fh/m8OrderFlowFh';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('order.flow.fh.m8OrderFlowFh');
  const { showMessage } = useMessage();
  const record = ref<M8OrderFlowFh>({} as M8OrderFlowFh);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增发货单') : t('编辑发货单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('客户编码'),
      field: 'cusCode',
      component: 'Select',
      componentProps: {
        dictType: 'M8_cus',
      },
      required: true,
    },
    {
      label: t('发货人'),
      field: 'sender.userCode',
      component: 'ListSelect',
      componentProps: {
        selectType: 'userSelect',
      },
      required: true,
    },
    {
      label: t('发货时间'),
      field: 'sendDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('收货人'),
      field: 'receiver.userCode',
      component: 'ListSelect',
      componentProps: {
        selectType: 'userSelect',
      },
    },
    {
      label: t('收货时间'),
      field: 'receiveAddress',
      component: 'Input',
      componentProps: {
        maxlength: 500,
      },
    },
    {
      label: t('联系电话'),
      field: 'iphone',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('物流单号'),
      field: 'logisticsNo',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('物流公司'),
      field: 'logistics',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('发货单子表'),
      field: 'm8OrderFlowFhRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'm8OrderFlowFhRdsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerM8OrderFlowFhRdsTable, m8OrderFlowFhRdsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleM8OrderFlowFhRdsDelete.bind(this, record),
          },
          auth: 'order:flow:fh:m8OrderFlowFh:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setM8OrderFlowFhRdsTableData(_res: Recordable) {
    m8OrderFlowFhRdsTable.setColumns([
      {
        title: t('订单ID'),
        dataIndex: 'order.id',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('图纸ID'),
        dataIndex: 'orderPic.id',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
      },
      {
        title: t('流程ID'),
        dataIndex: 'orderFlow.id',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: true,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 1000,
        },
        editRule: false,
      },
    ]);
    m8OrderFlowFhRdsTable.setTableData(record.value.m8OrderFlowFhRdsList || []);
  }

  function handleM8OrderFlowFhRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleM8OrderFlowFhRdsAdd() {
    m8OrderFlowFhRdsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleM8OrderFlowFhRdsDelete(record: Recordable) {
    m8OrderFlowFhRdsTable.deleteTableDataRecord(record);
  }

  async function getM8OrderFlowFhRdsList() {
    let m8OrderFlowFhRdsListValid = true;
    let m8OrderFlowFhRdsList: Recordable[] = [];
    for (const record of m8OrderFlowFhRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        m8OrderFlowFhRdsListValid = false;
      }
      m8OrderFlowFhRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of m8OrderFlowFhRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      m8OrderFlowFhRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!m8OrderFlowFhRdsListValid) {
      throw { errorFields: [{ name: ['m8OrderFlowFhRdsList'] }] };
    }
    return m8OrderFlowFhRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await m8OrderFlowFhForm(data);
    record.value = (res.m8OrderFlowFh || {}) as M8OrderFlowFh;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setM8OrderFlowFhRdsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djNo: record.value.djNo,
      };
      data.m8OrderFlowFhRdsList = await getM8OrderFlowFhRdsList();
      // console.log('submit', params, data, record);
      const res = await m8OrderFlowFhSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
